<!--收货（采购单）管理-->
<template>
  <div class="app-container">
    <el-form
      ref="form"
      inline
      :model="form"
      class="form-options"
      label-width="100px"
    >
      <!--需要修改成查询收货单号-->
      <el-form-item label="收货单号">
        <el-autocomplete
          ref="receiveNoRef"
          style="width: 200px"
          placeholder="请选择收货单号"
          v-model="form.receiveNo"
          value-key="name"
          :fetch-suggestions="querySearchReceiveNo"
          :trigger-on-focus="true"
          clearable
          @select="handleSelectReceiveNo"
          @clear="clickClearReceiveNo"
        />
      </el-form-item>
      <el-form-item label="鱼塘">
        <el-autocomplete
          ref="fishpondNameRef"
          style="width: 200px"
          placeholder="请选择鱼塘"
          v-model="form.fishpondName"
          value-key="name"
          :fetch-suggestions="querySearchFishpondName"
          :trigger-on-focus="true"
          clearable
          @select="handleSelectFishpondName"
          @clear="clickClearfishpondName"
        />
      </el-form-item>
      <el-form-item label="鱼品类型">
        <el-autocomplete
          ref="fishSpeciesRef"
          placeholder="请选择鱼品类型"
          v-model="form.fishSpecies"
          value-key="name"
          :fetch-suggestions="querySearchFishSpecies"
          :trigger-on-focus="true"
          clearable
          @select="handleSelectFishSpecies"
          @clear="clickClearfishSpecies"
        />
      </el-form-item>
      <el-form-item label="收货人">
        <el-autocomplete
          ref="receiverNameRef"
          placeholder="请选择收货人"
          v-model="form.receiverName"
          value-key="userName"
          :fetch-suggestions="querySysUser"
          :trigger-on-focus="true"
          clearable
          @select="handleSelectInName"
          @clear="clickClearfishSpecies"
        />
      </el-form-item>
      <el-form-item label="收货时间" class="long-content">
        <el-date-picker
          v-model="form.date"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          align="right"
        >
        </el-date-picker>
      </el-form-item>
      <div class="btns">
        <el-button
          type="primary"
          v-permission="['purchase_manage_query']"
          @click="onQuery"
          >查询</el-button
        >
        <el-button
          type="primary"
          v-permission="['purchase_manage_add']"
          @click="onAdd"
          >新增</el-button
        >
      </div>
    </el-form>
    <el-table
      :data="tableData"
      header-cell-class-name="table-header"
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column label="序号" type="index" width="45"> </el-table-column>
      <el-table-column prop="receiveNo" label="收货单号"> </el-table-column>
      <el-table-column prop="receiveTime" label="收货完成时间" width="135">
      </el-table-column>
      <el-table-column prop="fishpondName" label="鱼塘名称"> </el-table-column>
      <el-table-column prop="fishSpecies" label="鱼品种类"> </el-table-column>
      <el-table-column prop="sendWeight" label="送货重量(kg)" width="90">
      </el-table-column>
      <el-table-column prop="goodWeight" label="合格重量(kg)" width="90">
      </el-table-column>
      <el-table-column prop="goodRate" label="合格率(%)" width="80">
      </el-table-column>
      <el-table-column prop="receiverName" label="收货人" width="85">
      </el-table-column>
      <el-table-column prop="deliveryman" label="送货人" width="85">
      </el-table-column>
      <el-table-column prop="deliverymanPhone" label="送货人电话">
      </el-table-column>
      <el-table-column prop="createTime" label="建单时间" width="135">
      </el-table-column>
      <el-table-column
        prop="receiveRemark"
        label="收货备注"
        width="180"
        show-overflow-tooltip
      >
      </el-table-column>

      <el-table-column label="操作" width="68">
        <template slot-scope="scope">
          <el-button
            type="primary"
            v-permission="['purchase_manage_edit']"
            @click="handleOperateClick(scope.row, '修改')"
            >修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="text-align: right; margin-top: 20px">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 15, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog
      :title="dataFormTag + '送货单'"
      top="25px"
      v-if="dialogVisible"
      :visible.sync="dialogVisible"
      width="1300px"
    >
      <Purchase
        @onSave="onSave"
        @onAddEquipment="onAddEquipment"
        :type="disType"
        @onSubmit="onSubmit"
        :form="dataForm"
        ref="Purchase"
      />
      <span slot="footer">
        <el-button type="primary" v-if="!isOnlyRead" @click="saveData()"
          >保存</el-button
        >
        <el-button @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserCondition,
  getTypes,
  querySearchFishpondName,
  getFishTypeList,
} from "@/api/common";
import {
  getPurchaseOrders,
  getOrderNo,
  delPurchaseOrder,
  getImportAction,
  downExcelTemplate,
} from "@/api/purchase";
import Purchase from "../components/Purchase";
import WarehouseInComponent from "../components/WarehouseInComponent";
import { getName, getToken } from "@/utils/auth";
import { getIdsFromTreeData } from "@/utils/public";
import {
  delWarehouseEx,
  getBaseEquipmentType,
  getReceiveNos,
  getWarehouseInNo,
} from "@/api/warehouse";

export default {
  name: "PurchaseOrder",
  components: {
    Purchase,
    WarehouseInComponent,
  },
  data() {
    return {
      currentPage: 1,
      total: 0,
      pageSize: 10,
      form: {
        date: "",
        operName: "",
        purchaseName: "",
        orderStatus: "",
        receiverStartTime: "",
        receiverEndTime: "",
        receiveNo: "",
        batchNo: "",
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      loading: false,
      tableData: [],
      dialogVisible: false,
      purchaseOptions: [],
      isOnlyRead: false,
      dataForm: {},
      dataFormTag: "新增",
      disType: 2,
      warehouseInDialogVisible: false,
      warehouseInDataForm: {},
      importHeader: { Authorization: getToken() },
      importData: {},
      sysUsers: [],
      fishpond: [],
      sysFishs: [],
    };
  },
  created() {
    getUserCondition({}).then((res) => {
      this.sysUsers = res.resultData;
    });

    querySearchFishpondName({}).then((res) => {
      this.fishpond = res.resultData;
    });
    this.getFishTypeListFun();
    this.onQuery();
  },
  methods: {
    handleSizeChange: function (val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.getTableData();
    },
    handleCurrentChange: function (val) {
      this.currentPage = val;
      this.getTableData();
    },
    //获取收货单号，查询条件用
    querySearchReceiveNo: async function (queryString, cb) {
      let r = [];
      await getReceiveNos({ name: queryString }).then((res) => {
        r = res.resultData;
      });
      cb(r);
    },
    handleSelectReceiveNo(item) {
      this.form.receiveNo = item.name;
    },
    // 接口-鱼品下拉
    getFishTypeListFun() {
      getFishTypeList({ remark: 0 }).then((res) => {
        this.sysFishs = res.resultData;
      });
    },
    //获取鱼品类型
    querySearchFishSpecies: function (queryString, cb) {
      const r = this.sysFishs;
      // const r = [{"name":"黑鱼"},{"name":"鲈鱼"}]  //TODO lihuaibei 后台返回，确保系统一致，好修改
      var rs = queryString ? r.filter(this.createFilter(queryString)) : r;
      cb(rs);
    },
    handleSelectFishSpecies(item) {
      this.form.fishSpecies = item.name;
    },
    clickClearfishSpecies() {
      this.$nextTick(() => {
        if (this.$refs.fishSpeciesRef) {
          this.$refs.fishSpeciesRef.activated = true;
        }
      });
    },
    clickClearReceiveNo() {
      this.$nextTick(() => {
        if (this.$refs.receiveNoRef) {
          this.$refs.receiveNoRef.activated = true;
        }
      });
    },
    clickClearfishSpecies() {
      this.$nextTick(() => {
        if (this.$refs.receiverNameRef) {
          this.$refs.receiverNameRef.activated = true;
        }
      });
    },
    clickClearfishpondName() {
      this.$nextTick(() => {
        if (this.$refs.fishpondNameRef) {
          this.$refs.fishpondNameRef.activated = true;
        }
      });
    },
    //获取用户信息
    querySysUser: function (queryString, cb) {
      const r = this.sysUsers;
      // console.log(JSON.stringify(r)+"********************************");
      var rs = queryString
        ? r.filter(this.createFilterUserName(queryString))
        : r;
      cb(rs);
    },
    handleSelectSysUser(item) {
      this.form.qcName = item.userName;
    },

    //操作人员
    handleSelectInName(item) {
      this.form.inName = item.userName;
      this.form.inNameId = item.id;
    },

    querySearchFishpondName: function (queryString, cb) {
      const r = this.fishpond;
      var rs = queryString ? r.filter(this.createFilter(queryString)) : r;
      cb(rs);
    },
    handleSelectFishpondName(item) {
      this.form.fishpondName = item.name;
    },
    //模糊建议公共方法
    createFilter(queryString) {
      return (rr) => {
        return rr.name.toLowerCase().indexOf(queryString.toLowerCase()) != -1;
      };
    },
    createFilterUserName(queryString) {
      return (rr) => {
        return (
          rr.userName.toLowerCase().indexOf(queryString.toLowerCase()) != -1
        );
      };
    },
    onQuery() {
      this.currentPage = 1;
      this.getTableData();
    },
    getTableData() {
      if (this.form.date && this.form.date[0]) {
        this.form.receiverStartTime = this.form.date[0];
      } else {
        this.form.receiverStartTime = "";
      }
      if (this.form.date && this.form.date[1]) {
        this.form.receiverEndTime = this.form.date[1];
      } else {
        this.form.receiverEndTime = "";
      }
      const param = { page: this.currentPage, rows: this.pageSize, mark: "1" };
      Object.assign(param, this.form);
      getPurchaseOrders(param).then((res) => {
        this.tableData = res.resultData;
        this.total = res.total;
      });
    },

    onAdd() {
      this.dataFormTag = "新增";
      const a = new Promise((resolve) => {
        getOrderNo({ type: 1 }).then((res) => {
          resolve(res.resultData);
        });
      });
      const b = new Promise((resolve) => {
        getOrderNo({ type: 2 }).then((res) => {
          resolve(res.resultData);
        });
      });
      Promise.all([a, b]).then((res) => {
        this.dataForm = {
          id: "",
          receiveNo: res[1],
          receiveTime: "",
          supplierId: "",
          supplierName: "",
          fishpondName: "",
          fishpondId: "",
          fishSpecies: "",
          sendWeight: "",
          goodWeight: "",
          goodRate: "",
          receiverName: "",
          deliveryman: "",
          deliverymanPhone: "",
          receiveRemark: "",
          createTime: "",
        };
        this.dialogVisible = true;
        this.disType = 2;
      });
    },
    handleOperateClick(row, tag) {
      console.log("row---", row, tag);
      this.dataFormTag = tag;
      if (tag == "删除") {
        this.$confirm("确认删除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        }).then(() => {
          delPurchaseOrder({ id: row.id }).then((res) => {
            this.onQuery();
          });
        });
      } else if (tag == "查看") {
        this.queryDetail(row.id, true);
      } else if (tag == "修改") {
        this.queryDetail(row.id, false);
      }
    },
    queryDetail(id, isReadOnly) {
      const param = { page: 1, rows: 1, mark: "1", id: id };
      const a = [];

      const b = new Promise((resolve) => {
        getPurchaseOrders(param).then((res) => {
          resolve(res.resultData[0]);
        });
      });

      Promise.all([a, b]).then((res) => {
        const data = res[1];
        this.dataForm = {
          id: data.id,
          receiveNo: data.receiveNo,
          receiveTime: data.receiveTime,
          supplierId: data.supplierId,
          supplierName: data.supplierName,
          fishpondName: data.fishpondName,
          fishpondId: data.fishpondId,
          fishSpecies: data.fishSpecies,
          fishSpeciesId: data.fishSpeciesId,
          sendWeight: data.sendWeight,
          goodWeight: data.goodWeight,
          goodRate: data.goodRate,
          receiverName: data.receiverName,
          deliveryman: data.deliveryman,
          deliverymanPhone: data.deliverymanPhone,
          receiveRemark: data.receiveRemark,
          createTime: data.createTime,
        };

        this.disType = 1;
        this.dialogVisible = true;
      });
    },

    // --------------------分割--------------------

    querySearchName: function (queryString, cb) {
      // 调用 callback 返回建议列表的数据
      const results = [];
      getUserCondition({ userName: queryString, page: 1, rows: 20 }).then(
        (res) => {
          res.resultData.forEach((item) => {
            results.push({ id: item.id, value: item.userName });
          });
          cb(results);
        }
      );
    },
    handleSelectOperName(item) {
      this.form.operName = item.value;
    },
    handleSelectPurchaseName(item) {
      this.form.purchaseName = item.value;
    },

    addEquipment() {
      this.$refs["Purchase"].addEquipment();
    },
    onAddEquipment() {
      this.dialogVisible = false;
      this.onQuery();
    },
    saveData() {
      this.$refs["Purchase"].save();
    },
    onSave() {
      this.dialogVisible = false;
      this.onQuery();
    },
    saveWarehouseInData() {
      this.$refs["WarehouseInComponent"].save();
    },
    onWarehouseInSave() {
      this.warehouseInDialogVisible = false;
      this.onQuery();
    },
    submitData() {
      this.$refs["Purchase"].saveAndSubmit();
    },
    onSubmit() {
      this.dialogVisible = false;
      this.onQuery();
    },
    submitWarehouseInData() {
      this.$refs["WarehouseInComponent"].saveAndSubmit();
    },
    onWarehouseInSubmit() {
      this.warehouseInDialogVisible = false;
      this.onQuery();
    },

    onDownload() {
      window.location.href = downExcelTemplate();
    },
    getImportAction() {
      return getImportAction();
    },
    onUploadCallback(response, file, fileList) {
      // console.log(response)
      if (response.rCode == "200") {
        this.$message({
          type: "success",
          message: "导入数据成功",
        });
        this.onQuery();
      } else {
        this.$message({
          type: "error",
          message: response.rMsg,
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.line {
  text-align: center;
}
</style>
